package com.handytoo.cow.client;

import com.handytoo.cow.protocol.Protocol;
import com.handytoo.cow_core.network.Request.Request;
import com.handytoo.cow_core.network.Response.ClientResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class ClientHandler extends SimpleChannelInboundHandler<Request> {
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        // 连接建立时发送请求
        ServerProto.GetServerListRequest request = ServerProto.GetServerListRequest.newBuilder()
                .setType("dev")
                .build();
        // 序列化并发送请求
        ClientResponse clientResponse = new ClientResponse(Protocol.GetServerListRequest, request);
        ctx.writeAndFlush(clientResponse);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Request msg) {
        // 接收并反序列化响应
        System.out.println("Client received: " + msg.getCMD() +
                " length: " + msg.getLength());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
